package kr.ac.kaist.savehearts.ui;

import java.util.ArrayList;

import kr.ac.kaist.savehearts.SaveHeartsConstants;
import kr.ac.kaist.savehearts.auth.UserInfo;
import kr.ac.kaist.savehearts.status.StatusUpdateListener;
import kr.ac.kaist.savehearts.status.UserStatusUpdater;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class SignupActivity extends Activity 
	implements OnClickListener, OnFocusChangeListener, StatusUpdateListener {

	private static final String TAG = SignupActivity.class.getSimpleName();
	
	private Button buttonBack;
	private Button buttonOk;
	
	private EditText editTextFirstname;
	private EditText editTextLastname;
	private EditText editTextEmail;
	private EditText editTextPassword;
	private EditText editTextConfirm;
	private EditText editTextPhoneNumber;
	
	private ImageView imageViewPhoto;
	
	private Spinner spinnerType;
	
	private ProgressDialog dialog;
	
	private String userPicturePath;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signup);
		
		buttonBack = (Button)findViewById(R.id.buttonSignupBack);
		buttonBack.setOnClickListener(this);
		
		buttonOk = (Button)findViewById(R.id.buttonSignupOk);
		buttonOk.setOnClickListener(this);
		
		editTextFirstname = (EditText)findViewById(R.id.editTextSignupFirstname);
		editTextLastname = (EditText)findViewById(R.id.editTextSignupLastname);
		
		editTextEmail = (EditText)findViewById(R.id.editTextSignupEmail);
		editTextEmail.setOnFocusChangeListener(this);
		
		editTextPassword = (EditText)findViewById(R.id.editTextSignupPassword);
		editTextConfirm = (EditText)findViewById(R.id.editTextSignupPasswordConfirm);
		editTextPhoneNumber = (EditText)findViewById(R.id.editTextSignupPhoneNumber);
		
		imageViewPhoto = (ImageView)findViewById(R.id.imageViewSignupPhoto);
		imageViewPhoto.setOnClickListener(this);
		imageViewPhoto.setBackgroundResource(SaveHeartsConstants.USER_PICTURE_DEFAULT);
		
		editTextFirstname.requestFocus();
		
		spinnerType = (Spinner)findViewById(R.id.spinnerUserType);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, 
				R.array.user_type, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerType.setAdapter(adapter);
	}

	/**
	 * checkSignupForm() checks validity of user information in editTexts in sign up activity
	 * It checks first & last name, phone number, confirmation of password, and e-mail address.
	 * @return true: all user information is valid
	 * 		   false: there's something wrong with user information
	 */
	public boolean checkSignupForm() {
		Log.d(TAG, "checkSignupForm()");
		
		String firstName = editTextFirstname.getText().toString();
		String lastName = editTextLastname.getText().toString();
		String phoneNumber = editTextPhoneNumber.getText().toString();
		String psw = editTextPassword.getText().toString();
		String psw_confirm = editTextConfirm.getText().toString();
		String email = editTextEmail.getText().toString();
		
		// check all fields are filled or not
		if ( firstName.length() == 0 ) { editTextFirstname.requestFocus(); return false; }			
		if ( lastName.length() == 0 ) { editTextLastname.requestFocus(); return false; }
		if ( phoneNumber.length() == 0 ) { editTextPhoneNumber.requestFocus(); return false; }
		if ( psw.length() == 0 ) { editTextPassword.requestFocus(); return false; }
		if ( psw_confirm.length() == 0 ) { editTextConfirm.requestFocus(); return false; }
		if ( email.length() == 0 ) { editTextEmail.requestFocus(); return false; }
		
		// confirm the password
		if ( !psw.equals(psw_confirm) ) { editTextPassword.requestFocus(); return false; }
		
		// check validity of e-mail address
		if ( !email.matches(SaveHeartsConstants.EMAIL_PATTERN) ) { 
			editTextEmail.requestFocus();
			Log.e(TAG, "checkSignupForm(): Invalid e-mail address");
			return false;
		}
		
		// everything is fine!
		return true;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.buttonSignupOk:				
				// to validation of sign up form
				if ( !checkSignupForm() ) {
					// show error message
					AlertDialog errorDialog = new AlertDialog.Builder(this).create();
					errorDialog.setTitle(getString(R.string.signup));
					errorDialog.setMessage(getString(R.string.wront_signup_form));
					errorDialog.show();					
					return;
				}
				
				final String firstName = editTextFirstname.getText().toString();
				final String lastName = editTextLastname.getText().toString();
				final String phone = editTextPhoneNumber.getText().toString();
				final String passwd = editTextPassword.getText().toString();
				final String email = editTextEmail.getText().toString();
				
				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SignupActivity.this);
				
				// set title of the dialog
				dialogBuilder.setTitle(getString(R.string.signup));
				
				// set dialog message
				dialogBuilder
					.setMessage(getString(R.string.signup_confirm))
					.setCancelable(false)
					.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// sign up!
							UserStatusUpdater.getInstance().requestJoin(firstName, lastName,
									email, passwd, phone, SignupActivity.this, SignupActivity.this);
						}
					})
					.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// close the dialog
							dialog.cancel();
						}
					});
						
				// create alert dialog
				AlertDialog alertDialog = dialogBuilder.create();
				
				// show the dialog
				alertDialog.show();
				break;
				
			case R.id.buttonSignupBack:
				finish();
				break;
			
			case R.id.imageViewSignupPhoto:
				Intent myIntent = new Intent(Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				
				this.dialog = ProgressDialog.show(SignupActivity.this, "", getString(R.string.please_wait));
								
				startActivityForResult(myIntent, SaveHeartsConstants.IMAGE_PICK_REQUEST_CODE);
				break;
				
			default:
				break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if ( this.dialog != null ) this.dialog.dismiss();		
		this.dialog = null;
		
		switch ( requestCode ) {
			case SaveHeartsConstants.IMAGE_PICK_REQUEST_CODE:
				if ( resultCode == RESULT_OK ) {
					Uri selectedImage = data.getData();
					String[] filePathColumn = { MediaStore.Images.Media.DATA };
					
					Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
					cursor.moveToFirst();
					
					int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					String filePath = cursor.getString(columnIndex);
					userPicturePath = filePath;
					cursor.close();
					
					Bitmap userPhotoBitmap = BitmapFactory.decodeFile(filePath);
					Drawable userPhoto = new BitmapDrawable(userPhotoBitmap);
					imageViewPhoto.setBackgroundDrawable(userPhoto);
					
				} else {
					imageViewPhoto.setBackgroundResource(SaveHeartsConstants.USER_PICTURE_DEFAULT);
					userPicturePath = null;
				}
				break;
		}
	}

	@Override
	public void onFocusChange(View view, boolean arg) {
		switch (view.getId()) {
			case R.id.textViewLoginEmail:
				EditText emailTextView = (EditText)view;			
				String email = emailTextView.toString();
				if ( !email.matches(SaveHeartsConstants.EMAIL_PATTERN) ) {
					AlertDialog alertDialog = new AlertDialog.Builder(this).create();
					alertDialog.setTitle(getString(R.string.signup));
					alertDialog.setMessage(getString(R.string.wront_email));
					alertDialog.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
					alertDialog.show();
				}
				break;
			default:
				break;
		}
	}

	@Override
	public void neighborUpdated(ArrayList<UserInfo> neighbors) {
		// do nothing...		
	}

	@Override
	public void responseReceived(RequestType reqType, int response) {
		// TODO Auto-generated method stub
		
	}

}
